package com.example.http_url;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
//import javax.net.ssl.HttpsURLConnection;

public class HttpUtil {
    /**
     * 返回url对应网址的内容
     * @param sendurl
     * @return
     */
    public static String sendUrl(String sendUrl) {

        try {
            URL url = new URL(sendUrl);

            HttpURLConnection conn = null;
            BufferedReader reader = null;
            try {
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(5000);
                conn.setRequestMethod("GET");

                InputStream stream = conn.getInputStream();
                reader = new BufferedReader(new InputStreamReader(stream));
                StringBuffer buffer = new StringBuffer();
                String str = null;
                while ((str = reader.readLine()) != null) {
                    buffer.append(str);
                }
                return buffer.toString();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (reader != null){
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (conn != null){
                    conn.disconnect();
                }
            }
            //如果url无法被解析，发出异常
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
